// proxy.cpp
#include <zmq.hpp>
#include <iostream>
#include <string>
#include <queue>
#include <thread>
#include <chrono>

int main() {
    zmq::context_t context(1);
    zmq::socket_t frontend(context, ZMQ_XSUB);
    zmq::socket_t backend(context, ZMQ_XPUB);

    frontend.bind("tcp://*:5556");
    backend.bind("tcp://*:5555");

    std::cout << "Proxy started on ports 5555 and 5556" << std::endl;

    std::queue<zmq::message_t> message_cache;
    bool all_connected = false;

    while (true) {
        zmq::pollitem_t items[] = {
            {frontend, 0, ZMQ_POLLIN, 0},
            {backend, 0, ZMQ_POLLIN, 0}
        };

        zmq::poll(&items[0], 2, 100);

        if (items[1].revents & ZMQ_POLLIN) {
            zmq::message_t msg;
            backend.recv(msg, zmq::recv_flags::none);
            char* data = static_cast<char*>(msg.data());
            if (data[0] == 1) {
                // Subscription message
                all_connected = true;
                while (!message_cache.empty()) {
                    backend.send(message_cache.front(), zmq::send_flags::none);
                    message_cache.pop();
                }
            }
        }

        if (items[0].revents & ZMQ_POLLIN) {
            zmq::message_t msg;
            frontend.recv(msg, zmq::recv_flags::none);
            if (all_connected) {
                backend.send(msg, zmq::send_flags::none);
            } else {
                message_cache.push(msg);
            }
        }
    }

    return 0;
}
